//两数相加
//测试链接  https://leetcode.cn/problems/add-two-numbers/
public class AddTwoNumbers {
     public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(); //创建一个头节点
        ListNode tail = head; //记录尾指针
        int cnt = 0; //表示进位

        while(l1 != null || l2 != null || cnt != 0){
            int a = 0, b = 0;
            if(l1 != null){
                a = l1.val;
                l1 = l1.next;
            }
            if(l2 != null){
                b = l2.val;
                l2 = l2.next;
            }
            int  sum = a + b + cnt;
            int num = sum % 10;
            cnt = sum / 10;

            ListNode node  = new ListNode(num);
            tail.next = node;
            tail = tail.next;
        }
        return head.next;
    }
}
